import 'package:flutter/material.dart';

class FutureBuilderExample extends StatefulWidget {
  const FutureBuilderExample({Key? key}) : super(key: key);

  @override
  _FutureBuilderExampleState createState() => _FutureBuilderExampleState();
}

class _FutureBuilderExampleState extends State<FutureBuilderExample> {
  late Future<List<Employee>> _employeeFuture;

  @override
  void initState() {
    super.initState();
    // 在 initState 中调用并缓存 Future
    _employeeFuture = fetchEmployeesFromNetwork();
  }

  // 模拟一个异步网络请求，返回员工数据（30个员工）
  Future<List<Employee>> fetchEmployeesFromNetwork() async {
    await Future.delayed(const Duration(seconds: 2)); // 模拟网络延迟

    // 模拟返回的员工信息（30个员工）
    List<Map<String, dynamic>> employeesJson = List.generate(30, (index) {
      return {
        'name': 'Employee ${index + 1}',
        'position': 'Position ${['Manager', 'Developer', 'Designer', 'HR', 'Tester'][index % 5]}',
        'salary': 3000 + (index % 10) * 500, // 随机薪资
      };
    });

    // 将 JSON 转化为 Employee 对象并返回
    return employeesJson.map((json) => Employee.fromJson(json)).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('FutureBuilderExample')),
      body: FutureBuilder<List<Employee>>(
        future: _employeeFuture, // 使用缓存的 Future
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            // 正在加载
            return const Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            // 错误
            return Center(child: Text('Error: ${snapshot.error}'));
          } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
            // 没有数据
            return const Center(child: Text('No employees found.'));
          } else {
            // 数据加载成功
            List<Employee> employees = snapshot.data!;
            return ListView.builder(
              itemCount: employees.length, // 列表项数量
              itemBuilder: (context, index) {
                final employee = employees[index];
                return Card(
                  margin: const EdgeInsets.all(8.0),
                  child: ListTile(
                    title: Text(employee.name),
                    subtitle: Text('Position: ${employee.position}\nSalary: \$${employee.salary}'),
                  ),
                );
              },
            );
          }
        },
      ),
    );
  }
}

// 员工模型类
class Employee {
  final String name;
  final String position;
  final int salary;

  Employee({required this.name, required this.position, required this.salary});

  // 从 JSON 数据构造 Employee 对象
  factory Employee.fromJson(Map<String, dynamic> json) {
    return Employee(
      name: json['name'],
      position: json['position'],
      salary: json['salary'],
    );
  }
}
